package com.uniledger.exchange.home.scheme;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.king.zxing.CaptureActivity;
import com.uniledger.commonlib.util.ToastUtils;
import com.uniledger.exchange.R;
import com.uniledger.exchange.home.Glide4Engine;
import com.uniledger.exchange.home.StatusBarUtils;
import com.uniledger.languagelib.MultiLanguageUtil;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;

import java.util.List;

import butterknife.BindString;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * https://github.com/jenly1314/ZXingLite
 */
public class UniCaptureActivity extends CaptureActivity implements EasyPermissions.PermissionCallbacks {

    private static final int REQUEST_CODE_CHOOSE = 23;

    private static final String[] READ_AND_WRITE_STORAGE =
            {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final int RC_READ_AND_WRITE_STORAGE = 124;

    protected ImmersionBar mImmersionBar;

    @BindString(R.string.scan_bar_title)
    String title;

    @Override
    public int getLayoutId() {
        return R.layout.activity_uni_capture;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Toolbar toolbar = findViewById(R.id.toolbar);
        StatusBarUtils.immersiveStatusBar(this, toolbar, 0.2f);
        initBar();
        TextView tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText(title);
        getBeepManager().setPlayBeep(true);
        getBeepManager().setVibrate(true);
    }

    void initBar(){
        mImmersionBar = ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.colorPrimary);
        mImmersionBar.navigationBarColor(R.color.white);
        mImmersionBar.init();
    }

    private void offFlash() {
        Camera camera = getCameraManager().getOpenCamera().getCamera();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        camera.setParameters(parameters);
    }

    public void openFlash() {
        Camera camera = getCameraManager().getOpenCamera().getCamera();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        camera.setParameters(parameters);
    }

    private void clickFlash(View v) {
        if (v.isSelected()) {
            offFlash();
            v.setSelected(false);
        } else {
            openFlash();
            v.setSelected(true);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_sacn, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_menu_album:
                Toast.makeText(this, "选择图片", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        return true;
    }


    public void OnClick(View v) {
        switch (v.getId()) {
            case R.id.ivLeft:
                onBackPressed();
                break;
            case R.id.ivFlash:
                clickFlash(v);
                break;
            case R.id.tvAlbum://从相册选取图片
                pickIcon();
                break;
        }
    }

    /**
     * 判断是否有读写文件夹权限
     *
     * @return
     */
    private boolean hasReadAndWritePermissions() {
        return EasyPermissions.hasPermissions(this, READ_AND_WRITE_STORAGE);
    }

    @AfterPermissionGranted(RC_READ_AND_WRITE_STORAGE)
    public void pickIcon() {
        if (hasReadAndWritePermissions()) {
            // Have permission, do the thing!
            Matisse.from(this)
                    .choose(MimeType.ofAll(), false)
                    .countable(true)
                    .maxSelectable(1)
                    .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    .thumbnailScale(0.85f)
                    .imageEngine(new Glide4Engine())
                    .forResult(REQUEST_CODE_CHOOSE);

//            Toast.makeText(this, "TODO: Camera things", Toast.LENGTH_LONG).show();

        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(
                    this,
                    getString(R.string.permissions_storage),
                    RC_READ_AND_WRITE_STORAGE,
                    READ_AND_WRITE_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK &&
                requestCode == REQUEST_CODE_CHOOSE) {
            List<String> paths = Matisse.obtainPathResult(data);
            if (!paths.isEmpty())
                new DecoderTask().execute(paths.get(0));

        }
    }

    static class DecoderTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... strings) {
            return QRCodeDecoder.syncDecodeQRCode(strings[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            ToastUtils.show(s);
        }
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(MultiLanguageUtil.attachBaseContext(newBase));
    }
}
